package com.wangshaoyu.music_player.controller;

import com.wangshaoyu.music_player.repository.TrackRepo;
import com.wangshaoyu.music_player.session_object.UserSO;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.InputStream;

@Controller
@RequestMapping("/studio/track")
public class StudioTrackDoController {
    private final TrackRepo trackRepo;

    @Autowired
    public StudioTrackDoController(TrackRepo trackRepo) {
        this.trackRepo = trackRepo;
    }

    @PostMapping("/upload.do")
    @SneakyThrows
    public String upload(HttpServletRequest request, String title, MultipartFile content) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            UserSO user = (UserSO) session.getAttribute("currentUser");
            if (user != null) {
                String type = content.getContentType();
                InputStream is = content.getInputStream();

                trackRepo.insert1(user.uid, title, type, is);

                return "redirect:/studio/track/list.html";
            }
        }

        return "redirect:/studio/user/login.html";
    }
}
